﻿using Ivi.Visa;
using NationalInstruments.Visa;
using System.Reflection;
using TCommon;
using TCommunication.Interface;

namespace TCommunication.Impl;
/// <summary>
/// Visa通讯基类
/// </summary>
public class VisaCommunication:IVisaCommunication
{
    /// <summary>
    /// <see cref="IMessageBasedSession"/>会话对象
    /// </summary>
    public IMessageBasedSession? Session { get; set; }
    /// <summary>
    /// 资源名
    /// </summary>
    public string ResourceName { get; set; } = string.Empty;
    /// <summary>
    /// 是否连接
    /// </summary>
    public bool IsConnected => this.Session != null;
    /// <summary>
    /// 连接
    /// </summary>
    /// <returns></returns>
    public virtual OperateResult Connect()
    {
        Assembly.LoadFrom(".\\NationalInstruments.Common.dll");

        if (IsConnected)
        {
            return OperateResult.CreateSuccessResult();
        }
        using (var resourceManager = new ResourceManager())
        {
            try
            {
                this.Session = resourceManager.Open(ResourceName) as IMessageBasedSession;
            }
            catch (Exception e)
            {
                return OperateResult.CreateFailedResult(e.ToString());
            }
        }
        if (this.Session != null)
        {
            return OperateResult.CreateSuccessResult();
        }
        else
        {
            return OperateResult.CreateFailedResult("打开通讯失败");
        }
    }
    /// <summary>
    /// 断开连接
    /// </summary>
    /// <returns></returns>
    public virtual OperateResult DisConnect()
    {
        this.Session?.Clear();
        this.Session?.Dispose();
        return OperateResult.CreateSuccessResult();
    }
    /// <summary>
    /// 释放资源
    /// </summary>
    public void Dispose()
    {
        this.Session?.Dispose();
    }
}